﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using AutoMapper;
using SalesSys.WebCore.Authorize;
using WebGrease.Css.Extensions;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 钢厂管理
    /// </summary>
    [RoutePrefix("api/Supplier")]
    public class SupplierController : BaseApiController
    {
        private CommodityBLL commodityBLL = BllFactory.GetBll<CommodityBLL>();
        private SupplierBLL supplierBLL = BllFactory.GetBll<SupplierBLL>();

        /// <summary>
        /// 钢厂列表
        /// </summary>
        /// <param name="name">名称，模糊查询</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("List")]
        public ViewDtos<Supplier> GetList(string name = null, int page = 1, int rows = 10)
        {
            try
            {
                var re = supplierBLL.Select(name, GetRequestQuery());
                var dto = ViewDto.CreateList(re.Value);
                dto.Rows = rows;
                dto.Page = page;
                dto.Total = re.Key;
                return dto;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        /// <summary>
        /// 获取钢厂详情
        /// </summary>
        /// <param name="id">钢厂编号</param>
        /// <returns></returns>
        public Supplier Get(Guid id)
        {
            try
            {
                var re = supplierBLL.Details(id);

                return re;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 新增钢厂
        /// </summary>
        /// <param name="supplier">钢厂实体</param>
        public void Post(Supplier supplier)
        {
            if (string.IsNullOrWhiteSpace(supplier.Brand))
            {
                throw new ApiArgException("钢厂品牌不允许为空");
            }
            supplier.Commodities = null;
            var old = supplierBLL.GetList(p => p.Name == supplier.Name||p.Brand==supplier.Brand);
            if (old.Any())
            {
                throw new ApiArgException("重复的名称,钢厂名称及品牌不允许重复");
            }
            if (supplier.District != null)
            {
                supplier.District = BllFactory.GetBll<DistrictBLL>().Details(supplier.District.Id);
            }
            supplierBLL.Create(supplier);
            ProviderBLL providerBll = new ProviderBLL();
            providerBll.Create(supplier.ToProvider());
        }

        /// <summary>
        /// 修改钢厂
        /// </summary>
        /// <param name="supplier">钢厂实体</param>
        public void Put(Supplier supplier)
        {

            if (string.IsNullOrWhiteSpace(supplier.Brand))
            {
                throw new ApiArgException("钢厂品牌不允许为空");
            }
            supplier.Brand = supplier.Brand.Trim();
            var oldName = supplierBLL.GetList(p => (p.Name == supplier.Name||(p.Brand!=null&&p.Brand==supplier.Brand)) && p.Id != supplier.Id);
         
            if (oldName.Any())
            {
                throw new ApiArgException("重复的名称,钢厂名称及品牌不允许重复");
            }
            var old = supplierBLL.Details(supplier.Id);

            if (supplier.Brand != old.Brand)
            {
                old.Commodities.ForEach(p => p.Brand = supplier.Brand);
            }
            supplier.Commodities = old.Commodities;
            //CMapper.Map(supplier, old);
            if (supplier.District != null)
            {
                supplier.District = BllFactory.GetBll<DistrictBLL>().Details(supplier.District.Id);
            }
           
            supplierBLL.Edit(supplier);

        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="commoditys">商品列表</param>
        [Route("EditCommodity")]
        public void PutEditCommodity(Commodity[] commoditys)
        {
            var olds = commodityBLL.DetailsMany(commoditys.Select(p => p.Id).ToArray()).ToArray();
            foreach (var item in commoditys)
            {
                var old = olds.First(p => p.Id == item.Id);
                old.Name = item.Name;
                old.Format = item.Format;
                old.Brand = old.Supplier.Brand;
                old.RecordTime = DateTime.Now;
                old.Standard = item.Standard;
                old.Weight = item.Weight;
            }
            foreach (var item in olds)
            {
                commodityBLL.Edit(item);
            }

        }

        /// <summary>
        /// 添加钢厂商品
        /// </summary>
        /// <param name="supplierId">钢厂编号</param>
        /// <param name="commoditys">商品列表</param>
        [Route("AddCommodity")]
        public void PostAddCommodity(Guid supplierId, Commodity[] commoditys)
        {
            var sup = supplierBLL.Details(supplierId);
            var empbll = new EmployeeBLL();
            var emp = empbll.Details(ClientHelper.ClientInfo.Id);

            foreach (var item in commoditys)
            {
                var old = commodityBLL.GetList(p => p.Supplier.Id == supplierId && p.Name == item.Name && p.Format == item.Format && p.Standard == item.Standard);
                if (old.Any())
                {
                    throw new ApiArgException("产品名称重复");
                }
                item.Supplier = sup;
                item.Creater = emp;
                item.Brand = sup.Brand;
                item.RecordTime = DateTime.Now;
            }
            commodityBLL.Create(commoditys);
        }
        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="supplierId">钢厂编号</param>
        /// <param name="name">名称，模糊匹配</param>
        /// <param name="format">规格及标准，模糊匹配</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("Commodity")]
        public ViewDtos<Commodity> GetCommodity(Guid? supplierId = null, string name = null, string format = null, int page = 1, int rows = 10)
        {
            var data = commodityBLL.GetList(supplierId, name, format, page, rows);
            var dto = ViewDto.CreateList(data.Item2);
            dto.Page = page;
            dto.Rows = rows;
            dto.Total = data.Item1;
            return dto;
        }
        static IMapper _cMapper;
        static IMapper CMapper
        {
            get
            {
                if (_cMapper == null)
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Supplier, Supplier>();
                        cfg.ForAllPropertyMaps(p =>
                            !(typeof(IConvertible).IsAssignableFrom(p.SourceType)) || p.SourceMember.Name == "CreateTime"
                            , (p1, p2) =>
                                p2.Ignore());
                    });
                    config.CreateMapper();
                }
                return _cMapper;

            }
        }
    }
}
